﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Web.Routing;
using HRWEB.Models;

namespace HRWEB.Controllers
{
    public class ThesisController : Controller
    {
        hrdbEntities ent = new hrdbEntities();
        public ActionResult Index()
        {
            string id = HttpContext.Profile["ID"].ToString();
            return PartialView(ent.Theses.Where(p => p.EmployeeID == id).OrderByDescending(p=>p.Date));
        }
        
        [Authorize(Roles = "Admin")]
        public ActionResult AdminIndex(string id)
        {
            return PartialView("Index", ent.Theses.Where(p => p.EmployeeID == id).OrderByDescending(p => p.Date));
        }

        public ActionResult Edit()
        {
            string id = HttpContext.Profile["ID"].ToString();
            return View(ent.Theses.Where(p => p.EmployeeID == id).OrderByDescending(p => p.Date));
        }

        [Authorize(Roles="EduMaster")]
        public ActionResult AdminEdit(string id)
        {
            Session["CurrentID"] = id;
            return View("Edit", ent.Theses.Where(p => p.EmployeeID == id).OrderByDescending(p => p.Date));
        }
        public ActionResult Add(AddThesisModel model)
        {
            if (!string.IsNullOrEmpty(model.InputMaga))
            {
                var mags = ent.Magazines.Where(p => p.Name.Contains(model.InputMaga));
                model.Magazines = mags.ToList();
            }
            else
            {
                model.Magazines = new List<Magazine>();
            }
            Thesis thesis = model.NewThesis;
            if (thesis != null && model.SelectedMagaNO != 0&&!string.IsNullOrEmpty(thesis.Title))
            {
                string id;
                if (Session["currentID"] != null)
                {
                    id = Session["currentID"].ToString();
                }
                else
                {
                    id = HttpContext.Profile["ID"].ToString();
                }
                thesis.EmployeeID = id;
                thesis.MSerialNO = model.SelectedMagaNO;
                ent.Theses.Add(thesis);
                ent.SaveChanges();
                return RedirectToAction("AdminEdit", new { id = id });
            }
            model.NewThesis = ent.Theses.Create();
            model.NewThesis.Date = DateTime.Now;
            return PartialView(model);
        }
        [HttpPost]
        public ActionResult ListMagazines(string name)
        {
            if (string.IsNullOrEmpty(name))
                return View("Add");
            var mags = ent.Magazines.Where(p => p.Name.Contains(name));
            ViewBag.Name = name;
            return View("Index", mags);
        }
        [HttpPost]
        public ActionResult RealAdd(AddThesisModel atm)
        {
            if (Session["CurrentID"] == null)
            {
                return RedirectToAction("Edit");
            }
            else
            {
                string id = Session["CurrentID"].ToString();
                return RedirectToAction("AdminEdit", new { id = id });
            }
        }
        public ActionResult Back()
        {
            if (Session["CurrentID"] == null || string.IsNullOrEmpty(Session["CurrentID"].ToString())) return RedirectToAction("Index", "DetailInfo");
            RouteValueDictionary di = new RouteValueDictionary();
            di.Add("id", Session["CurrentID"].ToString());
            return Redirect(UrlHelper.GenerateUrl(null, "ViewEmployee", "Admin", null, null, "JPInfo", di, Url.RouteCollection, Url.RequestContext, false));
        }
        
        public ActionResult Delete(int serial)
        {
            var it = ent.Theses.Find(serial);
            if (!it.Confirmed)
            {
                if (!string.IsNullOrEmpty(it.Filename))
                {
                    string fullPath = Path.Combine(GetPath(), it.Filename);
                    if (System.IO.File.Exists(fullPath)) System.IO.File.Delete(fullPath);
                }
                ent.Theses.Remove(it);
                ent.SaveChanges();
            }
            return RedirectToAction("Edit");
        }
        public ActionResult Select(int serial, bool isMaster)
        {
            var it = ent.Theses.Find(serial);
            it.Selected = !it.Selected;
            ent.SaveChanges();
            if (isMaster)
                return RedirectToAction("AdminEdit", new { id = it.EmployeeID });
            else
                return RedirectToAction("Edit");
        }
        [Authorize(Roles="EduMaster")]
        public ActionResult AdminDelete(int serial)
        {
            var it = ent.Theses.Find(serial);
            if (!it.Confirmed)
            {
                if (!string.IsNullOrEmpty(it.Filename))
                {
                    string fullPath = Path.Combine(GetPath(), it.Filename);
                    if (System.IO.File.Exists(fullPath)) System.IO.File.Delete(fullPath);
                }
                ent.Theses.Remove(it);
                ent.SaveChanges();
            }
            return RedirectToAction("AdminEdit", new { id = it.EmployeeID });
        }
        [Authorize(Roles="EduMaster")]
        public ActionResult Confirm(int serial)
        {
            var it = ent.Theses.Find(serial);
            it.Selected = false;
            it.Confirmed = !it.Confirmed;
            ent.SaveChanges();
            return RedirectToAction("AdminEdit", new { id = it.EmployeeID });
        }
        private string GetPath()
        {
            return Server.MapPath("~/CertFiles/Thesis");
        }
        public ActionResult UploadThesis(int serial)
        {
            string path = GetPath();
            HttpPostedFileBase file = Request.Files[0];
            string ext = Path.GetExtension(file.FileName);
            if (file != null && serial != 0)
            {
                var ee = ent.Theses.Where(p => p.SerialNO == serial).Single();
                if (ee.Confirmed) return null;
                var bb = ent.TEmployees.Where(p => p.FEmployeeID == ee.EmployeeID).Single();
                string filname = bb.FPublicID + " " + bb.FName.Trim() + " " + ee.Title.Trim() + " " + ext;
                if (!string.IsNullOrEmpty(ee.Filename))
                {
                    string oriFullName = Path.Combine(path, ee.Filename);
                    if (System.IO.File.Exists(oriFullName)) System.IO.File.Delete(oriFullName);
                }
                string fullName = Path.Combine(path, filname);
                if (System.IO.File.Exists(fullName)) { System.IO.File.Delete(fullName); }
                file.SaveAs(fullName);
                ee.Filename = filname;
                ent.SaveChanges();
            }
            return null;
        }
    }
}
